package com.whz.governance.promethus;

import io.prometheus.client.exporter.BasicAuthHttpConnectionFactory;
import io.prometheus.client.exporter.DefaultHttpConnectionFactory;
import io.prometheus.client.exporter.HttpConnectionFactory;
import io.prometheus.client.exporter.PushGateway;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * @author whz
 */
@Configuration
@ConditionalOnProperty(name = PushGatewayProperties.PRFIX + ".enable", havingValue = "true")
@EnableConfigurationProperties(PushGatewayProperties.class)
public class PushGatewayAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public PushGateway createPushGateWayClient(PushGatewayProperties pushGatewayProperties, @Autowired(required = false)
    HttpConnectionFactory httpConnectionFactory) {
        HttpConnectionFactory http = httpConnectionFactory;
        Assert.hasText(pushGatewayProperties.getAddress(), "address NOT blank.");
        if (http == null) {
            if (!StringUtils.isEmpty(pushGatewayProperties.getUserName()) &&
                !StringUtils.isEmpty(pushGatewayProperties.getPassword())) {
                http = new BasicAuthHttpConnectionFactory(pushGatewayProperties.getUserName(),
                                                          pushGatewayProperties.getPassword());
            } else {
                http = new DefaultHttpConnectionFactory();
            }
        }
        PushGateway pushgateway = new PushGateway(pushGatewayProperties.getAddress());
        pushgateway.setConnectionFactory(http);
        return pushgateway;
    }

    @Bean
    @ConditionalOnMissingBean
    public PrometheusPostProcessor createPrometheusPostProcessor() {
        return new PrometheusPostProcessor();
    }
}